package com.zjn.config;

import com.zjn.mapper.UserMapper;
import com.zjn.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;


//自动移的UserRealm
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;

    /*授权
    *   获取角色权限信息*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权方法->doGetAuthorizationInfo");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        /*为当前对象赋予perms权限*/
//        info.addStringPermission("emp:emp");
        //1. 拿到当前登录的对象
        Subject subject = SecurityUtils.getSubject();
        //2. 取出下面认证类最后存入SimpleAuthenticationInfo中的值：即为当前用户
        User currentUser = (User) subject.getPrincipal();
        //3. 设置当前用户权限
        info.addStringPermission(currentUser.getPerms());
        return info;
    }

    /*认证
    *   获取用户凭证信息*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证方法->doGetAuthenticationInfo");
        //获取token
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //连接真实的数据库
        User user = new User();
        user.setUserCode(token.getUsername());      //从token中获取用户名
        user = userMapper.queryUserByUser(user);
        //没有这个用户
        if (user == null) {
            return null;    //相当于UnknownAccountException异常
        }
        //密码认证，这里已经不显示密码验证而是由shiro自己来做
        return new SimpleAuthenticationInfo(user, user.getUserPassword(), "");
    }
}
